//
//  AnnotationClusterViewController.m
//  operation4ios
//
//  Created by kjlink on 16/8/29.
//  Copyright © 2016年 阳光电源股份有限公司. All rights reserved.
//

#import "AnnotationClusterViewController.h"
#import "CoordinateQuadTree.h"
#import "ClusterAnnotation.h"
#import "ClusterAnnotationView.h"
#import "CustomCalloutView.h"

@interface AnnotationClusterViewController ()<CustomCalloutViewTapDelegate>

/** 地图层级(0-国家，1-省，2-市，3-县) */
@property (nonatomic,copy)NSString *map_level;
/** 电站名称 */
@property (nonatomic,copy)NSString *ps_id;
/** 自定义插图 */
@property (nonatomic, strong) CustomCalloutView *customCalloutView;

@property (nonatomic, strong) CoordinateQuadTree *coordinateQuadTree;
@property (nonatomic, assign) BOOL shouldRegionChangeReCalculate;
@property (nonatomic,strong)NSMutableArray *annotations;
/** 定位按钮  */
@property (nonatomic,strong)UIButton *goCurrentLocation;
/** 保存点击的标注试图 */
@property (nonatomic,strong) ClusterAnnotationView *annotationview;

@end

@implementation AnnotationClusterViewController

- (NSMutableArray *)annotations {
    if (!_annotations) {
        _annotations = [NSMutableArray array];
    }
    return _annotations;
}


#pragma mark - update Annotation
/**
 7.
 */
/* 更新annotation. */
- (void)updateMapViewAnnotationsWithAnnotations:(NSArray *)annotations
{
//    NSLog(@"更新annotation.");
    /* 用户滑动时，保留仍然可用的标注，去除屏幕外标注，添加新增区域的标注 */
    NSMutableSet *before = [NSMutableSet setWithArray:self.mapView.annotations];
    [before removeObject:[self.mapView userLocation]];
    NSSet *after = [NSSet setWithArray:annotations];
    
    /* 保留仍然位于屏幕内的annotation. */
    NSMutableSet *toKeep = [NSMutableSet setWithSet:before];
    [toKeep intersectSet:after];
    
    /* 需要添加的annotation. */
    NSMutableSet *toAdd = [NSMutableSet setWithSet:after];
    [toAdd minusSet:toKeep];
    
    /* 删除位于屏幕外的annotation. */
    NSMutableSet *toRemove = [NSMutableSet setWithSet:before];
    [toRemove minusSet:after];
    
    /* 更新. */
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mapView addAnnotations:[toAdd allObjects]];
        [self.mapView removeAnnotations:[toRemove allObjects]];
    });
}
/**
 2.
 */
/**
 6.
 */
- (void)addAnnotationsToMapView:(MAMapView *)mapView
{
    @synchronized(self)
    {
        if (self.coordinateQuadTree.root == nil || !self.shouldRegionChangeReCalculate)
        {
            NSLog(@"tree is not ready.");
            return;
        }
        MAMapRect rect = mapView.visibleMapRect;
        double zoomScale = self.mapView.bounds.size.width / rect.size.width;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            /* 根据当前zoomLevel和zoomScale 进行annotation聚合. */
            NSArray *annotations = [self.coordinateQuadTree clusteredAnnotationsWithinMapRect:rect
                                                                                withZoomScale:zoomScale
                                                                                 andZoomLevel:mapView.zoomLevel];
            /* 更新annotation. */
            [self updateMapViewAnnotationsWithAnnotations:annotations];
        });
    }
}


//加载数据
- (void)loadPoiData {
    self.goCurrentLocation.selected = NO;
    self.mapView.showsUserLocation = NO;
}


#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    
    if (![view isKindOfClass:[ClusterAnnotationView class]]) return;
    ClusterAnnotation *annotation = (ClusterAnnotation *)view.annotation;
    [mapView setCenterCoordinate:annotation.coordinate animated:YES];
    
//    当地图缩放到最大级别后，仍有电站重合，则以轮播效果显示，否则点击放大地图
    if (mapView.zoomLevel < 19.0f && annotation.pois.count > 1) {
        [mapView deselectAnnotation:annotation animated:NO];
        [self plusClick:nil];
        return;
    }
    
    for (MapPS *mapPs in annotation.pois)
    {
        [self.selectedPoiArray addObject:mapPs];
    }
    
    _annotationview = (ClusterAnnotationView *)view;
    [_annotationview.btn setBackgroundImage:IMAGE(@"blue-icon") forState:UIControlStateNormal];
    [self.customCalloutView setMapPsArr:self.selectedPoiArray];
    self.customCalloutView.delegate = self;
    
    [self.view addSubview:self.customCalloutView];
}

- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    [self.selectedPoiArray removeAllObjects];
    [self.customCalloutView dismissCalloutView];
    self.customCalloutView.delegate = nil;

}

/**
 1.地图缩放
 */
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    if (_annotationview) {
        ClusterAnnotation *annotation = (ClusterAnnotation *)_annotationview.annotation;
        if (annotation.pois.count > 1) {
            [_annotationview.btn setBackgroundImage:IMAGE(@"solid-icon") forState:UIControlStateNormal];
        }
    }
    [self addAnnotationsToMapView:self.mapView];
}
/**
 8.
 */
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
//    NSLog(@"viewForAnnotation");
    if ([annotation isKindOfClass:[ClusterAnnotation class]])
    {
        /* dequeue重用annotationView. */
        static NSString *const AnnotatioViewReuseID = @"AnnotatioViewReuseID";
        
        ClusterAnnotationView *annotationView = (ClusterAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotatioViewReuseID];
        
        if (!annotationView)
        {
            annotationView = [[ClusterAnnotationView alloc] initWithAnnotation:annotation
                                                               reuseIdentifier:AnnotatioViewReuseID];
        }
        
        /* 设置annotationView的属性. */
        annotationView.annotation = annotation;
        annotationView.count = [(ClusterAnnotation *)annotation count];
//    给标注传数据，使只有一个标注时，显示电站名称
        if (annotationView.count == 1) {
            MapPS *mapPs = [[(ClusterAnnotation *)annotation pois] firstObject];
            annotationView.mapPsModel = mapPs;
        }else{
            annotationView.mapPsModel = nil;
        }
        
        [self.mapView showAnnotations:_annotations animated:YES];
        /* 不弹出原生annotation */
        annotationView.canShowCallout = NO;
        
        return annotationView;
    }
    
    return nil;
}

#pragma mark - SearchPOI
-(void)creatZuoBiao:(NSArray *)ZuoBiao{
    if (ZuoBiao.count == 0)
    {
        return;
    }
    
    @synchronized(self)
    {
        self.shouldRegionChangeReCalculate = NO;
        
        // 清理
        [self.selectedPoiArray removeAllObjects];
        [self.customCalloutView dismissCalloutView];
        [self.mapView removeAnnotations:self.mapView.annotations];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 1. 此处给出坐标点
            /* 建立四叉树. */
            [self.coordinateQuadTree buildTreeWithPOIs:ZuoBiao];
            self.shouldRegionChangeReCalculate = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
            [self addAnnotationsToMapView:self.mapView];
            });
        });
    }
    
}
#pragma mark - Life Cycle
/**
 0.
 */
- (id)init
{
//    NSLog(@"init");
    if (self = [super init])
    {
        self.coordinateQuadTree = [[CoordinateQuadTree alloc] init];
        self.selectedPoiArray = [NSMutableArray array];
        self.customCalloutView = [[CustomCalloutView alloc]init];
    }
    
    return self;
}
/**
 3.
 */
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.shouldRegionChangeReCalculate = NO;
    
    [self setupMap];

    /**
     下面数组里放字典，字典里面放你要给的活动点经纬度
     */
}

- (void)setupMap {
    
    UIButton *refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [refreshBtn addTarget:self action:@selector(loadPoiData) forControlEvents:UIControlEventTouchUpInside];
    // 设置图片
    [refreshBtn setBackgroundImage:IMAGE(@"refresh") forState:UIControlStateNormal];
    // 设置尺寸
    refreshBtn.frame = CGRectMake(0, 0, 20, 16);
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:refreshBtn] animated:YES];
    
    UIButton *minusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [minusBtn setImage:IMAGE(@"hotel_btn_controls_minus") forState:UIControlStateNormal];
    [minusBtn setImage:IMAGE(@"hotel_btn_controls_minus_disable") forState:UIControlStateDisabled];
    [minusBtn setImage:IMAGE(@"hotel_btn_controls_minus_pressed") forState:UIControlStateHighlighted];
    [minusBtn addTarget:self action:@selector(minusClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:minusBtn];
    
    [minusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-50);
        make.bottom.mas_equalTo(-30);
        make.width.mas_equalTo(35);
    }];
    
    UIButton *plusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [plusBtn setImage:IMAGE(@"hotel_btn_controls_plus") forState:UIControlStateNormal];
    [plusBtn setImage:IMAGE(@"hotel_btn_controls_plus_disable") forState:UIControlStateDisabled];
    [plusBtn setImage:IMAGE(@"hotel_btn_controls_plus_pressed") forState:UIControlStateHighlighted];
    [plusBtn addTarget:self action:@selector(plusClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:plusBtn];
    
    [plusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(minusBtn.right);
        make.bottom.mas_equalTo(minusBtn.bottom);
        make.top.mas_equalTo(minusBtn.top);
        make.width.mas_equalTo(35);
    }];
    
    self.goCurrentLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    self.goCurrentLocation.selected = NO;
    [self.goCurrentLocation setImage:[UIImage imageNamed:@"dest_map_btn_location_20x20"] forState:UIControlStateNormal];
    self.goCurrentLocation.adjustsImageWhenHighlighted = NO;
    [self.goCurrentLocation addTarget:self action:@selector(locActionAndreGeocodeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.goCurrentLocation];
    [self.goCurrentLocation makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(minusBtn.centerY);
        make.left.mas_equalTo(15);
        make.height.width.mas_equalTo(35);
    }];
}

#pragma mark - Action Handle
//定位地址
- (void)locActionAndreGeocodeAction:(UIButton *)btn {
    self.mapView.showsUserLocation = !btn.selected;
    if (!btn.selected) {
        self.mapView.showsUserLocation = YES;
        self.mapView.userTrackingMode = MAUserTrackingModeFollowWithHeading;
    } else {
        self.mapView.showsUserLocation = NO;
    }
    btn.selected = !btn.selected;
    
//    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        if (error) {
//            [HTLoading showErrorWithTitle:@"定位失败"];
//            if (error.code == AMapLocationErrorLocateFailed) {
//                return;
//            }
//        }
//        
//        if (location && regeocode) {
//            [self minusClick:nil];
//            [self.mapView setCenterCoordinate:location.coordinate animated:YES];
//        }
//    }];
}

- (void)minusClick:(UIButton *)btn {
    [self.mapView setZoomLevel:(self.mapView.zoomLevel - 1.5f) animated:YES];
}

- (void)plusClick:(UIButton *)btn {
    [self.mapView setZoomLevel:(self.mapView.zoomLevel + 1.5f) animated:YES];
}

- (void)dealloc
{
    NSLog(@"dealloc");
    [self.coordinateQuadTree clean];
}

#pragma mark - CustomCalloutViewTapDelegate

- (void)didDetailButtonTapped:(NSInteger)index
{
    [self clickDetailButtonIndex:index];
}

- (void)clickDetailButtonIndex:(NSInteger)index {
    
}

@end
